package com.yang.sso.oauth2.oauth.handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.yang.common.core.result.R;
import org.yang.common.i18n.constant.I18nMessageConstant;

import java.io.IOException;

/**
 * 自定义认证失败处理
 * @author: lslands
 * @description:
 * @version：v1.0
 * @date: 2024/6/3 11:13
 */
@Slf4j
@Component
public class Oauth2FailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message;
        if (exception instanceof OAuth2AuthenticationException auth2AuthenticationException) {
            OAuth2Error error = auth2AuthenticationException.getError();
            message = error.getErrorCode();
        } else {
            message = exception.getMessage();
        }
        log.error("【认证信息错误】:{}",message);
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.getWriter().write(JSONObject.toJSONString(new R<>(false,401,message)));
        response.getWriter().flush();

    }
}

